import React, { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
/**
 * 在文件上传之前，一定会执行这个函数
 * @param {*} file 选中的文件
 * @returns 
 */
const beforeUpload = (file) => {
    console.log(file);
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    // 最终得到结果MB > KB >Byte
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    //执行图片其他操作，比如裁剪等等

    return isJpgOrPng && isLt2M;
};
const MyUpload = ({uploadFile,name,action,filePath=null}) => {
    const [loading, setLoading] = useState(false);
    //保存你点击按钮处理过后的图片，可以用于回显
    const [imageUrl, setImageUrl] = useState();
    //选中了一个文件过后，得到文件上传状态
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            console.log(info.file);
            getBase64(info.file.originFileObj, (url) => {
                console.log("加密过后base64地址",url);
                setLoading(false);
                setImageUrl(url);
            });
            const fileName = info.file.response.data;
            uploadFile(fileName)
        }
    };
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                点击上传
            </div>
        </button>
    );
    
    return (
        <Flex gap="middle" wrap>
            <Upload
                name={name}
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={true}
                action={action}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl || filePath ? (
                    <img
                        src={imageUrl || filePath}
                        alt="avatar"
                        style={{
                            width: '100%',
                        }}
                    />
                ) : (
                    uploadButton
                )}
            </Upload>
        </Flex>
    );
};
export default MyUpload;